//
//  CatBluViewController.m
//  EquesCat
//
//  Created by Chun Hung Cheung on 2024/12/17.
//

#import "CatBluViewController.h"
#import "BlufiClient.h"
#import "ESPFBYBLEHelper.h"
#import "ESPDataConversion.h"
#import <iconv.h>
#import "YKWiFiListVController.h"
#import "BindSuccessViewController.h"
@interface CatBluViewController ()<UITextFieldDelegate,BlufiDelegate,CBPeripheralDelegate,CBCentralManagerDelegate,BindSuccessViewControllerDelegate>
@property(nonatomic,strong)UILabel *selectedWiflLabel;
@property(nonatomic,strong)UITextField *wifi_Name_TextField;
@property(nonatomic,strong)UITextField *wifi_password_TextField;
@property(nonatomic,strong)UIButton *nextButton;
@property(nonatomic,strong)UIButton *tipsButton;
@property(nonatomic,strong)UIAlertController *alertController;

//蓝牙连接
@property(strong, nonatomic)BlufiClient *blufiClient;
@property (nonatomic,strong)ESPPeripheral *blu_devies;
@property(nonatomic, strong)ESPFBYBLEHelper *espFBYBleHelper;
@property(nonatomic, copy) NSString *filterContent;

//设备bid
@property(nonatomic, copy) NSString *devicesid;


//蓝牙连接状态
@property(assign, atomic)BOOL connected;


/*存储设备返回的Wi-Fi列表*/
@property(nonatomic,strong)NSArray *wifi_array;

/*搜索设备超时*/
@property (nonatomic,strong) dispatch_source_t scan_timeout_timer;
/*绑定设备超时*/
@property (nonatomic,strong) dispatch_source_t wait_timer;

//计数
@property(nonatomic,assign)int  postBluMessage;

@property(nonatomic,strong)NSData *post_data;

@property(nonatomic,strong)BindSuccessViewController *sucess_vc;
@end

@implementation CatBluViewController

- (void)viewDidLoad {
    [super viewDidLoad];

     self.view.backgroundColor = [UIColor whiteColor];
    [self setup];
    
    
        
    __weak CatBluViewController *weakSelf = self;
    self.espFBYBleHelper = [ESPFBYBLEHelper share];
    self.espFBYBleHelper.bleScanSuccessBlockStatus = ^(CBManagerState status) {
   
        NSLog(@"status-->%ld",(long)status);
        if (status == CBManagerStatePoweredOn) {
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (weakSelf.alertController) {
                   [weakSelf.alertController dismissViewControllerAnimated:YES completion:nil];
                }
                
                [SVProgressHUD showWithStatus:NSLocalizedString(@"扫描Wi-Fi中", nil)];
            }];
        }else if(status == CBManagerStateUnauthorized){
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (weakSelf.alertController) {
                   [weakSelf.alertController dismissViewControllerAnimated:YES completion:nil];
                }
                weakSelf.alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"APP蓝牙权限未开启，绑定智能锁需要开启蓝牙权限，请前往APP应用设置里打开蓝牙权限", nil) preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"去开启", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                  [weakSelf.navigationController popViewControllerAnimated:YES];
                    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                    [[UIApplication sharedApplication] openURL:url];
                }];
                [weakSelf.alertController addAction:deleteButton];
                [weakSelf presentViewController:weakSelf.alertController animated:YES completion:nil];
            }];
        }else if(status == CBManagerStatePoweredOff){
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (weakSelf.alertController) {
                   [weakSelf.alertController dismissViewControllerAnimated:YES completion:nil];
                }
                weakSelf.alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"手机蓝牙功能未打开，绑定智能锁时需要请打开手机的蓝牙功能", nil) preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [weakSelf.navigationController popViewControllerAnimated:YES];
                }];
                [weakSelf.alertController addAction:deleteButton];
                [weakSelf presentViewController:weakSelf.alertController animated:YES completion:nil];
            }];
        }
    };

    self.filterContent = [ESPDataConversion loadBlufiScanFilter];
   
   //开始扫描设备
   [self scanDeviceInfo];
        
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    
    if (_scan_timeout_timer) {
        dispatch_source_cancel(_scan_timeout_timer);
        _scan_timeout_timer = nil;
    }
    __block int timeout = 30;
    __weak CatBluViewController *weakSelf = self;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _scan_timeout_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_scan_timeout_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_scan_timeout_timer, ^{
       
        timeout--;
        NSLog(@"scan WiFi timeout-->%d",timeout);
        
        if(timeout == 10 && !self.connected){
            NSLog(@"connect device again");
            if (!weakSelf.blufiClient.closed) {
                [weakSelf.blufiClient connect:weakSelf.blu_devies.uuid.UUIDString];
            }
        }
        
        if (timeout <= 0) {
           
            if (weakSelf.scan_timeout_timer) {
               dispatch_source_cancel(weakSelf.scan_timeout_timer);
                weakSelf.scan_timeout_timer = nil;
            }
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [self.espFBYBleHelper stopScan];
                 self.espFBYBleHelper = nil;
                
                if(self.wifi_array.count == 0){
                   if([SVProgressHUD isVisible]){
                     [SVProgressHUD dismiss];
                   }
                  [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"扫描Wi-Fi失败，请重新扫描", nil) duration:2];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }
            }];
        }
    });
    dispatch_resume(_scan_timeout_timer);
    
}


- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    [self.espFBYBleHelper stopScan];
     self.espFBYBleHelper = nil;
    
    if([SVProgressHUD isVisible]){
       [SVProgressHUD dismiss];
    }
}




//文案显示
-(UILabel*)selectedWiflLabel
{
     if (!_selectedWiflLabel) {
         _selectedWiflLabel = [[UILabel alloc]init];
         _selectedWiflLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:28.0];
         _selectedWiflLabel.numberOfLines = 0;
         _selectedWiflLabel.textAlignment = NSTextAlignmentLeft;
        [_selectedWiflLabel sizeToFit];
         _selectedWiflLabel.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
        [self.view addSubview:_selectedWiflLabel];
        [_selectedWiflLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top).offset(50+[UIDevice dev_navigationFullHeight]);
            make.left.equalTo(self.view.mas_left).offset(28);
        }];
    }
    return _selectedWiflLabel;
}


-(UITextField*)wifi_Name_TextField
{

    if (!_wifi_Name_TextField) {
        _wifi_Name_TextField = [[UITextField alloc]init];
        _wifi_Name_TextField.delegate = self;
        _wifi_Name_TextField.borderStyle = UITextBorderStyleNone;
        _wifi_Name_TextField.textColor = [UIColor blackColor];
        _wifi_Name_TextField.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
        _wifi_Name_TextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _wifi_Name_TextField.tag = 1234;
        NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"Please input network", nil) attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:16]}];
                 _wifi_Name_TextField.attributedPlaceholder = placeholderString;
    
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0,0,40,20)];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn setImage:[UIImage imageNamed:@"vl0_form_switch"] forState:UIControlStateNormal];
        _wifi_Name_TextField.rightViewMode = UITextFieldViewModeAlways;
        _wifi_Name_TextField.rightView = btn;
        
        [self.view addSubview:_wifi_Name_TextField];
        [_wifi_Name_TextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(28);
            make.right.equalTo(self.view.mas_right).offset(-28);
            make.top.equalTo(self.selectedWiflLabel.mas_bottom).offset(60);
            make.height.mas_equalTo(44);
        }];

    }
    return _wifi_Name_TextField;

}

-(void)btnClick:(UIButton*)sender
{
    [self.view endEditing:YES];
    
    if(self.wifi_array.count > 0){
        
        YKWiFiListVController *wifilist = [[YKWiFiListVController alloc] initWithType:kWHCustomAnimationTypePresent];
        self.definesPresentationContext = YES;
        wifilist.wifiarray = [NSArray arrayWithArray:self.wifi_array];
        wifilist.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];
        wifilist.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        wifilist.selectedBlock = ^(NSString * _Nonnull wifi) {
            NSLog(@"选中返回的Wi-Fi-->%@",wifi);
            self.wifi_Name_TextField.text = wifi;
        };
       [self.navigationController presentViewController:wifilist animated:YES completion:nil];
    }else{
     
       [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Failed to scan WiFi, please re-trigger the device to enter the distribution network mode", nil) duration:4];
    }
}




-(UITextField*)wifi_password_TextField
{
    if (!_wifi_password_TextField) {
         _wifi_password_TextField = [[UITextField alloc]init];
         _wifi_password_TextField.delegate = self;
         _wifi_password_TextField.textColor = [UIColor blackColor];
         _wifi_password_TextField.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
         _wifi_password_TextField.placeholder = NSLocalizedString(@"Enter the network password", nil);
          NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"Enter the network password", nil) attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:16]}];
                  _wifi_password_TextField.attributedPlaceholder = placeholderString;
         [self.view addSubview:_wifi_password_TextField];
        
        
         UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0,0,40,20)];
        [btn addTarget:self action:@selector(wifi_password_TextFieldClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn setImage:[UIImage imageNamed:@"vl0_form_show"] forState:UIControlStateNormal];
        _wifi_password_TextField.rightViewMode = UITextFieldViewModeAlways;
        _wifi_password_TextField.rightView = btn;
        
        [_wifi_password_TextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(28);
            make.right.equalTo(self.view.mas_right).offset(-28);
            make.top.equalTo(self.wifi_Name_TextField.mas_bottom).offset(33);
            make.height.mas_equalTo(44);
        }];

         _wifi_password_TextField.tag = 3456;
         _wifi_password_TextField.borderStyle = UITextBorderStyleNone;
         _wifi_password_TextField.leftViewMode = UITextFieldViewModeAlways;
         _wifi_password_TextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    }
    return _wifi_password_TextField;
    
}

- (void)wifi_password_TextFieldClick:(UIButton*)sender
{
    sender.selected = !sender.selected;
    _wifi_password_TextField.secureTextEntry = sender.selected;
    if (sender.selected) {
        [sender setImage:[UIImage imageNamed:@"vl0_form_hide"] forState:UIControlStateNormal];
    }else{
        [sender setImage:[UIImage imageNamed:@"vl0_form_show"] forState:UIControlStateNormal];
    }
}

-(UIButton*)nextButton
{
     if (!_nextButton) {
         _nextButton =[UIButton buttonWithType:UIButtonTypeCustom];
        [_nextButton addTarget:self action:@selector(nextButtonButtonBtnclick) forControlEvents:UIControlEventTouchUpInside];
         _nextButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:20.0];
         _nextButton.layer.cornerRadius = 25;
         _nextButton.layer.masksToBounds = YES;
        [self.view addSubview:_nextButton];
        [_nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(280);
            make.height.mas_equalTo(50);
            make.bottom.equalTo(self.view.mas_bottom).offset(-120);
            make.centerX.equalTo(self.view.mas_centerX);
        }];
    }
    
    return _nextButton;
}



- (void)nextButtonButtonBtnclick
{
    
    if (_scan_timeout_timer) {
        dispatch_source_cancel(_scan_timeout_timer);
        _scan_timeout_timer = nil;
    }
    
      NSString *main_ip,*sub_ip;
      YKIPinfo *appinfo = [[YKIPinfo bg_find:@"YKIPinfo" where:nil] firstObject];
      if(appinfo.mainip){
          main_ip = appinfo.mainip;
          sub_ip = appinfo.subip;
      }
     
        NSLog(@"main_ip-->%@ sub_ip--%@",main_ip,sub_ip);
    

        NSTimeZone *zone =  [NSTimeZone systemTimeZone];
        NSInteger timeOff = [zone secondsFromGMT];
        NSInteger timeMin = timeOff/60;//相差分钟数
        NSInteger zone2 = timeMin/60;//相差时区
        NSLog(@"timeOff == %ld timeMin == %ld zone2 == %ld\n",timeOff,timeMin,zone2);
        NSString *timezone;
        if(timeMin % 60 == 0){
            
            if(zone2 > 0){
                timezone = [NSString stringWithFormat:@"+%ld",(long)zone2];
            }else if(zone2 == 0){
                timezone = @"0";
            }else{
                timezone = [NSString stringWithFormat:@"%ld",(long)zone2];
            }
            
        }else{
        
            NSInteger zone3 = timeMin % 60;//相差分钟
            NSInteger zone2 = timeMin / 60;//相差小时
            
            if(zone2 > 0){
                timezone = [NSString stringWithFormat:@"+%ld:%ld",(long)zone2,zone3];
            }else if(zone2 == 0){
                timezone = [NSString stringWithFormat:@"0:%ld",(long)zone3];
            }else{
                timezone = [NSString stringWithFormat:@"%ld:%ld",(long)zone2,zone3];
            }
        }

    
    if(self.wifi_Name_TextField.text.length > 0 && self.wifi_password_TextField.text.length > 0){
       
    
        [self add_bind_timer];
       
         NSData *data = [self bind_strWifi_name:self.wifi_Name_TextField.text wifi_pwd:self.wifi_password_TextField.text main_ip:main_ip sub_ip:sub_ip timezone:timezone strdns:@"" is_screen:NO lock_id:nil];
        [self.blufiClient postCustomData:data];
        
    }else{
        
        if(self.wifi_Name_TextField.text.length > 0){
      
            UIAlertController *alter = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Note", nil) message:NSLocalizedString(@"Make sure the Wi-Fi password at home is empty", nil) preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel",nil)  style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
            UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
      
                
                [self add_bind_timer];
                
                NSData *data = [self bind_strWifi_name:self.wifi_Name_TextField.text wifi_pwd:@"" main_ip:main_ip sub_ip:sub_ip timezone:timezone strdns:@"" is_screen:NO lock_id:nil];
                [self.blufiClient postCustomData:data];
                
            }];
            [alter addAction:cancel];
            [alter addAction:deleteButton];
            
            [self presentViewController:alter animated:YES completion:nil];
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Please input network", nil) duration:3];
        }
    }
}


- (NSData*)bind_strWifi_name:(NSString*)wifi_name  wifi_pwd:(NSString*)Wifi_pwd main_ip:(NSString*)main_ip sub_ip:(NSString*)sub_ip timezone:(NSString*)timezone strdns:(NSString*)strdns is_screen:(BOOL)is_screen  lock_id:(NSString*)lock_id
{

    YKIPinfo *appinfo = [[YKIPinfo bg_find:@"YKIPinfo" where:nil] firstObject];
    
    
    // is_overseas 是否是海外 海外隐藏默认语音 isMainLand 1 代表是否是国内
    // thirdPartyId 客户品牌ID
    // colony 服务器集群信息id
    // colony_addr 服务器集群信息地址
    // ssid Wi-Fi名称
    // pwd Wi-Fi密码
    // time_zone 时区信息
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:wifi_name forKey:@"ssid"];
    [dict setValue:Wifi_pwd forKey:@"pwd"];
    [dict setValue:[Tooles getuserToken] forKey:@"user_name"];
    [dict setValue:timezone forKey:@"time_zone"];
    [dict setValue:@(![appinfo.isMainLand intValue]) forKey:@"is_overseas"]; //宠物配网是否是海外
    [dict setValue:@(ThirdPartyDemoBrand) forKey:@"thirdPartyId"];
    
    if(appinfo.mainip){
        [dict setValue:main_ip forKey:@"main_ip"];
        [dict setValue:sub_ip forKey:@"sub_ip"];
    }
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    int colony = [[userDefaults objectForKey:@"colony"] intValue];
    NSString *colony_addr = [userDefaults objectForKey:@"colony_addr"];
  
    if (colony_addr.length  > 0) {
       [dict setValue:@(colony) forKey:@"colony"];
       if (colony > 5) {
          [dict setValue:colony_addr forKey:@"colony_addr"];
       }
    }
    
    NSError *error;
    // 将字典转换为 JSON 数据
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
  
    self.post_data = jsonData;
    
    NSLog(@"dict -- %@",dict);
    
    return jsonData;
    
}


- (void)add_bind_timer
{
    [SVProgressHUD showWithStatus: NSLocalizedString(@"绑定设备中", nil)];
    
    __weak CatBluViewController *weakSelf = self;
    __block int timeout = 30;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _wait_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_wait_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_wait_timer, ^{
    
        timeout--;
        
        NSLog(@"bind devices timeout -->%d",timeout);
        
        //超时再发一遍配网信息
        if (timeout == 20 && self.post_data.length > 0){
            [self.blufiClient postCustomData:self.post_data];
        }
        
        if (timeout <= 0) {
            
            if (weakSelf.wait_timer) {
               dispatch_source_cancel(weakSelf.wait_timer);
                weakSelf.wait_timer = nil;
            }
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                [self.espFBYBleHelper stopScan];
                 self.espFBYBleHelper = nil;
                if([SVProgressHUD isVisible]){
                   [SVProgressHUD dismiss];
                }
                
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Binding timeout, please check whether the WiFi password is correct!", nil) duration:3];
                
            }];
        }
    });
    dispatch_resume(_wait_timer);
}




- (void)setup
{
     self.title = NSLocalizedString(@"设置网络", nil);
     UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
     backbtn.frame = CGRectMake(0,0,80,40);
     backbtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0f];
     backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [backbtn setTitle:NSLocalizedString(@"返回", nil) forState:UIControlStateNormal];
    [backbtn setTitleColor:[HexChangeRGB colorWithHexString:@"#4c4c4c"] forState:UIControlStateNormal];
    [backbtn setImage: [UIImage imageNamed:@"button_back_lightgray_arrow"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftAction) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];

  
     self.selectedWiflLabel.text = NSLocalizedString(@"选择Wi-Fi", nil);
     self.wifi_Name_TextField.placeholder = NSLocalizedString(@"输入Wi-Fi名称", nil);
     self.wifi_password_TextField.placeholder = NSLocalizedString(@"输入Wi-Fi密码", nil);
    [self.nextButton setTitle:NSLocalizedString(@"下一步", nil) forState:UIControlStateNormal];
     self.nextButton.backgroundColor = [UIColor orangeColor];
    [self.nextButton setTitleColor:[HexChangeRGB colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
}

- (void)selectLeftAction
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)scanDeviceInfo {
     NSLog(@"start search blu devices");
    [self.espFBYBleHelper startScan:^(ESPPeripheral * _Nonnull device) {
        NSLog(@"blu search device.uuid-->%@",device.uuid);
        if ([self shouldAddToSource:device]) {
            [self.espFBYBleHelper stopScan];
             NSLog(@"device.uuid-->%@",device.uuid);
             NSLog(@"device.name-->%@",device.name);
            [self connect:device];
        }
    }];
}

- (BOOL)shouldAddToSource:(ESPPeripheral *)device {
    // Check filter
    if (self.blue_mac.length > 0) {
    
        if (_filterContent && _filterContent.length > 0) {
            if (!device.name || ![device.name hasPrefix:_filterContent] || ![device.name isEqualToString:[NSString stringWithFormat:@"BLUFI_VL4%@",self.blue_mac]]) {
                // The device name has no filter prefix
                return NO;
            }
        }
        
        return YES;
    }else{
        
        if (_filterContent && _filterContent.length > 0) {
            if (!device.name || ![device.name hasPrefix:_filterContent]) {
                // The device name has no filter prefix
                return NO;
            }
        }
        return YES;
        
    }
}


// 去连接
- (void)connect:(ESPPeripheral*)device {
    
     if (_blufiClient) {
        [_blufiClient close];
         _blufiClient = nil;
      }
    
       _blufiClient = [[BlufiClient alloc] init];
       _blufiClient.isVL2 = NO;
       _blufiClient.isVM6 = [device.name containsString:@"WS3"] ? YES : NO;
       _blufiClient.centralManagerDelete = self;
       _blufiClient.peripheralDelegate = self;
       _blufiClient.blufiDelegate = self;
       self.blu_devies = device;
     [_blufiClient connect:device.uuid.UUIDString];
}


#pragma mark centralManagerDelete
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    
    NSLog(@"Connected device \n");
    self.connected = YES;

    
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    NSLog(@"Connet device failed \n");
    self.connected = NO;
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    [self onDisconnected];
     NSLog(@"Disconnected device \n");
     self.connected = NO;
}

- (void)onDisconnected {
    if (_blufiClient) {
       [_blufiClient close];
    }
}


//蓝牙连好 可以发送数据等操作
- (void)blufi:(BlufiClient *)client gattPrepared:(BlufiStatusCode)status service:(CBService *)service writeChar:(CBCharacteristic *)writeChar notifyChar:(CBCharacteristic *)notifyChar {
    NSLog(@"Blufi gattPrepared status:%d", status);
    if (status == StatusSuccess) {
         self.connected = YES;
         NSLog(@"BluFi connection has prepared \n");
        
        NSString *cusData = [NSString stringWithFormat:@"{\"method\":\"wifilist\"}"];
        NSData *data = [cusData dataUsingEncoding:NSUTF8StringEncoding];
       [self.blufiClient postCustomData:data];
    
    } else {
        [self onDisconnected];
        if (!service) {
            NSLog(@"Discover service failed");
        } else if (!writeChar) {
            NSLog(@"Discover write char failed");
        } else if (!notifyChar) {
            NSLog(@"Discover notify char failed");
        }
    }
}

- (void)blufi:(BlufiClient *)client didNegotiateSecurity:(BlufiStatusCode)status {
    NSLog(@"Blufi didNegotiateSecurity %d", status);
    if (status == StatusSuccess) {
        NSLog(@"Negotiate security complete");
    } else {
        NSLog(@"Negotiate security failed: %d",status);
    }
}

- (void)blufi:(BlufiClient *)client didReceiveDeviceVersionResponse:(BlufiVersionResponse *)response status:(BlufiStatusCode)status {

    if (status == StatusSuccess) {
        NSLog(@"%@",[NSString stringWithFormat:@"Receive device version: %@",response.getVersionString]);
    } else {
        NSLog(@"%@",[NSString stringWithFormat:@"Receive device version error: %d", status]);
    }
}

- (void)blufi:(BlufiClient *)client didPostConfigureParams:(BlufiStatusCode)status {
    if (status == StatusSuccess) {
        NSLog(@"Post configure params complete");
    } else {
        NSLog(@"%@",[NSString stringWithFormat:@"Post configure params failed: %d", status]);
    }
}

- (void)blufi:(BlufiClient *)client didReceiveDeviceStatusResponse:(BlufiStatusResponse *)response status:(BlufiStatusCode)status {
  
    if (status == StatusSuccess) {
        NSLog(@"%@",[NSString stringWithFormat:@"Receive device status:\n%@", response.getStatusInfo]);
    } else {
        NSLog(@"%@",[NSString stringWithFormat:@"Receive device status error: %d", status]);
    }
}

- (void)blufi:(BlufiClient *)client didReceiveDeviceScanResponse:(NSArray<BlufiScanResponse *> *)scanResults status:(BlufiStatusCode)status {
  
    if (status == StatusSuccess) {
        NSMutableString *info = [[NSMutableString alloc] init];
        [info appendString:@"Receive device scan results:\n"];
        for (BlufiScanResponse *response in scanResults) {
            [info appendFormat:@"SSID: %@, RSSI: %d\n", response.ssid, response.rssi];
        }
        NSLog(@"%@",info);
    } else {
        NSLog(@"%@",[NSString stringWithFormat:@"Receive device scan results error: %d", status]);
    }
}

- (void)blufi:(BlufiClient *)client didPostCustomData:(nonnull NSData *)data status:(BlufiStatusCode)status {
    if (status == StatusSuccess) {
         NSLog(@"发送自定义数据成功Post custom data complete \n");
        // 发送数据成功
    } else {
         NSLog(@"%@",[NSString stringWithFormat:@"Post custom data failed: %d", status]);
    }
}

- (void)blufi:(BlufiClient *)client didReceiveCustomData:(NSData *)data status:(BlufiStatusCode)status {
    NSString *customString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",[NSString stringWithFormat:@"Receive device custom data: %@", customString]);
    
    if (!customString) {
         customString = [[NSMutableString alloc]initWithData:[self cleanUTF8:data] encoding:NSUTF8StringEncoding];
         NSLog(@"cleanUTF8 str2-->%@ \n",customString);
    }
    
    
    if (!customString) {
         customString = [self convertedToUtf8String:data];
         NSLog(@"convertedToUtf8String str2-->%@ \n",customString);
    }
    
    
    
    NSDictionary *dict  = [Tooles jsonAnalysis:customString];
    NSLog(@"jsonAnalysis after-->%@",dict);
    
    /*
     {
       2022-12-27 18:06:19.523869+0800 DoorBell[27115:10898700] str-->start
       2022-12-27 18:06:19.527188+0800 DoorBell[27115:10898700] str-->{"count":21,"list":"[{\"ssid\":\"LINK_test\",\"rssi\":-34},{\"ssid\":\"DIRECT-g5DESKTOP-155OPPHmsOR\",\"rssi\":-35},{\"ssid\":\"Banker-WiFi\",\"rssi\":-36},{\"ssid\":\"999\",\"rssi\":-39},{\"ssid\":\"EQUES_UniFi\",\"rssi\":-44},{\"ssid\":\"HW破网!@#￥%*2.4G\",\"rssi\":-46},{\"ssid\":\"lynlyn007\",\"rssi\":-46},{\"ssid\":\"TP-LINK_D5EE\",\"rssi\":-48},{\"ssid\":\"device-test\",\"rssi\":-49},{\"ssid\":\"yikang移康研发01\",\"rssi\":-50},{\"ssid\":\"ChinaNet-3m2z\",\"rssi\":-52},{\"ssid\":\"TP-LINK_2B07\,\"rssi\":-52},{\"ssid\":\"ChinaNet-39EP\",\"rssi\":-55},{\"ssid\":\"ps\",\"rssi\":-57},{\"ssid\":\"eques-home\",\"rssi\":-57},{\"ssid\":\"MONA\",\"rssi\":-63},{\"ssid\":\"DIRECT-CC-HP Laser 178nw\",\"rssi\":-65},{\"ssid\":\"UPGRADE-AP\",\"rssi\":-65},{\"ssid\":\"test007\",\"rssi\":-68},{\"ssid\":\"CU_rB2P\",\"rssi\":-71},{\"ssid\":\"MERCURY_76A6\",\"rssi\":-59}]"}
        2022-12-27 18:06:19.530486+0800 DoorBell[27115:10898700] str-->end
     
     */
      
    if([customString containsString:@"eques_wifi_config"]){
        
       NSLog(@"绑定结果receive-- %@",customString);
        
     //{"eques_wifi_config":{"describe":"e55bd61707105650205b02f004a254c5","status":0}}
        
        
       NSDictionary *dict = [Tooles jsonAnalysis:customString];
        /*
            {"eques_wifi_config":{"describe":"e55bd61707105650205b02f004a254c5","status":0}}
            Status（值 int 类型） Describe（string 类型）
            0 绑定成功的   describe: 32的设备bid
            1 未找到 WiFi
            2 WiFi 密码错误
            3 设备获取路由 IP 错误
            4 设备无法连接 WiFi
            5 设备登录失败
            6 设备绑定失败
            7 设备连接服务器失败
        */
        
        if([SVProgressHUD isVisible]){
           [SVProgressHUD dismiss];
        }
        
        if (_wait_timer) {
           dispatch_source_cancel(_wait_timer);
            _wait_timer = nil;
        }
        
        NSDictionary *dict2 = [dict objectForKey:@"eques_wifi_config"];
        int code = [[dict2 objectForKey:@"status"] intValue];
        NSString *title;
        NSString *subtitle;
        
        switch (code) {
                
            case 0:
            {
                
                if(!self.devicesid){
                   
                     //绑定成功后 重新获取下设备列表
                    [YKBusinessFramework equesGetDeviceList];
                    
                    self.devicesid = [dict2 objectForKey:@"describe"];
                    
                    [self removeTimer];
           
                     self.sucess_vc = [[BindSuccessViewController alloc]init];
                     self.sucess_vc.delegate = self;
                     self.sucess_vc.optionstr = @"Cat";
                     self.sucess_vc.modalPresentationStyle = UIModalPresentationFullScreen;
                    [self.view.window.rootViewController presentViewController:self.sucess_vc animated:YES completion:^{
                    }];
                   
                }
                
            }
                break;
                
            case 1:
            {
                
             title = NSLocalizedString(@"WiFi not found", nil);
             subtitle = NSLocalizedString(@"WiFi signal is bad, please enter correct WiFi name", nil);
            }
                break;
                
            case 2:
            {
                title = NSLocalizedString(@"WiFi password error", nil);
                subtitle = NSLocalizedString(@"Please enter the correct WiFi password", nil);
            }
                break;
            case 3:
            {
                title = NSLocalizedString(@"Device get route IP error", nil);
                subtitle = NSLocalizedString(@"WiFi connection error or device cannot connect to WiFi, please restart the router to try", nil);
                
            }
                break;
            case 4:
            {
                title = NSLocalizedString(@"The device cannot connect to WiFi", nil);
                subtitle = NSLocalizedString(@"Other exceptions encountered when connecting to WiFi, please restart the router to try", nil);
            }
                break;
            case 5:
            {
                title = NSLocalizedString(@"Device login failed", nil);;
                subtitle = @"";
            }
                break;
            case 6:
            {
                title = NSLocalizedString(@"Device binding failed", nil);
                subtitle = @"";
            }
                break;
            case 7:
            {
                title = NSLocalizedString(@"The device failed to connect to the server", nil);
                subtitle = NSLocalizedString(@"WiFi cannot connect to the internet. Please make sure WiFi can connect to the internet", nil);
            }
                break;
            default:
                break;
        }
    

        /*
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           
            if(code != 0){
                self.failView = [[YKLowBatteryView alloc]initwithTitle:title subtitle:subtitle];
                self.failView.delegate = self;
               [[UIApplication sharedApplication].keyWindow addSubview:self.failView];
               [self.failView show];
            }
        });
        */
        return;
    }
    
    if([[dict objectForKey:@"count"] intValue] == 0){
        
        self.postBluMessage ++;
        if(self.postBluMessage == 1){
            
            
            NSString *cusData = [NSString stringWithFormat:@"{\"method\":\"wifilist\"}"];
            NSData *data = [cusData dataUsingEncoding:NSUTF8StringEncoding];
           [self.blufiClient postCustomData:data];
            return;
        }else{
            [SVProgressHUD showErrorWithStatus:@"设备搜索WiFi列表返回为空，请重新扫描！" duration:3];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
            return;
        }
    }
    
    
    if([[dict objectForKey:@"count"] intValue] > 0){
        
        NSArray *strarray;
        if([customString containsString:@"\"[{"] && [customString containsString:@"}]\""]){
        
            NSString *no_format_str  = [dict objectForKey:@"list"];
            NSString *str1 = [no_format_str stringByReplacingOccurrencesOfString:@"[" withString:@""];
            NSString *str3 = [str1 stringByReplacingOccurrencesOfString:@"]" withString:@""];
            NSArray *Arrat = [str3 componentsSeparatedByString:@","];

            NSMutableArray *array = [NSMutableArray array];
            
            if(Arrat.count % 2 == 0 && Arrat.count > 0){
                for (int i = 1; i <= Arrat.count; i ++) {
                    if(i % 2 == 0){
                        NSString *str = [NSString stringWithFormat:@"%@,%@",Arrat[i-2],Arrat[i-1]];
                        NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
                        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves  error:nil];
                        [array addObject:responseJSON];
                    }
                }
                strarray = [NSArray arrayWithArray:array];
            }
        }else{
            strarray = [dict objectForKey:@"list"];
        }

        if(strarray.count){
            
            if (_scan_timeout_timer) {
               dispatch_source_cancel(_scan_timeout_timer);
                _scan_timeout_timer = nil;
            }
            
            // 创建一个NSSortDescriptor对象，指定要排序的key为"age"
            NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"rssi" ascending:YES comparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                NSNumber *number1 = [NSNumber numberWithInteger:labs([(NSNumber *)obj1 integerValue])];
                NSNumber *number2 = [NSNumber numberWithInteger:labs([(NSNumber *)obj2 integerValue])];
                return [number1 compare:number2];
            }];

            // 使用sortDescriptor对数组进行排序
            NSArray *sortedArray = [strarray sortedArrayUsingDescriptors:@[sortDescriptor]];
            
            
             NSLog(@"dict2Wi-Fi-->%@",sortedArray);
            
             self.wifi_array = [NSArray arrayWithArray:sortedArray];
            
            [SVProgressHUD dismiss];
            
            YKWiFiListVController *wifilist = [[YKWiFiListVController alloc] initWithType:kWHCustomAnimationTypePresent];
            self.definesPresentationContext = YES;
            wifilist.wifiarray = [NSArray arrayWithArray:sortedArray];
            wifilist.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];
            wifilist.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            wifilist.selectedBlock = ^(NSString * _Nonnull wifi) {
                NSLog(@"选中返回的Wi-Fi-->%@",wifi);
                
                self.wifi_Name_TextField.text = wifi;
            
            };
           [self.navigationController presentViewController:wifilist animated:YES completion:nil];
            
        }
    }
}


/**
 剔除非UTF-8字符
 @param data 原来的数据data
 @return 处理后的输入data
 */
- (NSData *)cleanUTF8:(NSData *)data
{
    iconv_t cd = iconv_open("UTF-8", "UTF-8"); // 从UTF-8转UTF-8
    int one = 1;
    iconvctl(cd, ICONV_SET_DISCARD_ILSEQ, &one); // 剔除非UTF-8的字符

    size_t inbytesleft, outbytesleft;
    inbytesleft = outbytesleft = data.length;
    char *inbuf  = (char *)data.bytes;
    char *outbuf = malloc(sizeof(char) * data.length);
    char *outptr = outbuf;
    if (iconv(cd, &inbuf, &inbytesleft, &outptr, &outbytesleft)
        == (size_t)-1) {
        NSLog(@"this should not happen, seriously");
        return nil;
    }
    NSData *result = [NSData dataWithBytes:outbuf length:data.length - outbytesleft];
    iconv_close(cd);
    free(outbuf);
    return result;
}

-(NSString *)convertedToUtf8String:(NSData*)data{
    
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (string == nil) {
        string = [[NSString alloc] initWithData:[self UTF8Data:data] encoding:NSUTF8StringEncoding];
    }
    return string;
    
}

-(NSData *)UTF8Data:(NSData*)data{
    
    //保存结果
    NSMutableData *resData = [[NSMutableData alloc] initWithCapacity:data.length];
    
    NSData *replacement = [@"�" dataUsingEncoding:NSUTF8StringEncoding];
    
    uint64_t index = 0;
    const uint8_t *bytes = data.bytes;
    
    long dataLength = (long) data.length;
    
    while (index < dataLength) {
        uint8_t len = 0;
        uint8_t firstChar = bytes[index];
        
        // 1个字节
        if ((firstChar & 0x80) == 0 && (firstChar == 0x09 || firstChar == 0x0A || firstChar == 0x0D || (0x20 <= firstChar && firstChar <= 0x7E))) {
            len = 1;
        }
        // 2字节
        else if ((firstChar & 0xE0) == 0xC0 && (0xC2 <= firstChar && firstChar <= 0xDF)) {
            if (index + 1 < dataLength) {
                uint8_t secondChar = bytes[index + 1];
                if (0x80 <= secondChar && secondChar <= 0xBF) {
                    len = 2;
                }
            }
        }
        // 3字节
        else if ((firstChar & 0xF0) == 0xE0) {
            if (index + 2 < dataLength) {
                uint8_t secondChar = bytes[index + 1];
                uint8_t thirdChar = bytes[index + 2];
                
                if (firstChar == 0xE0 && (0xA0 <= secondChar && secondChar <= 0xBF) && (0x80 <= thirdChar && thirdChar <= 0xBF)) {
                    len = 3;
                } else if (((0xE1 <= firstChar && firstChar <= 0xEC) || firstChar == 0xEE || firstChar == 0xEF) && (0x80 <= secondChar && secondChar <= 0xBF) && (0x80 <= thirdChar && thirdChar <= 0xBF)) {
                    len = 3;
                } else if (firstChar == 0xED && (0x80 <= secondChar && secondChar <= 0x9F) && (0x80 <= thirdChar && thirdChar <= 0xBF)) {
                    len = 3;
                }
            }
        }
        // 4字节
        else if ((firstChar & 0xF8) == 0xF0) {
            if (index + 3 < dataLength) {
                uint8_t secondChar = bytes[index + 1];
                uint8_t thirdChar = bytes[index + 2];
                uint8_t fourthChar = bytes[index + 3];
                
                if (firstChar == 0xF0) {
                    if ((0x90 <= secondChar & secondChar <= 0xBF) && (0x80 <= thirdChar && thirdChar <= 0xBF) && (0x80 <= fourthChar && fourthChar <= 0xBF)) {
                        len = 4;
                    }
                } else if ((0xF1 <= firstChar && firstChar <= 0xF3)) {
                    if ((0x80 <= secondChar && secondChar <= 0xBF) && (0x80 <= thirdChar && thirdChar <= 0xBF) && (0x80 <= fourthChar && fourthChar <= 0xBF)) {
                        len = 4;
                    }
                } else if (firstChar == 0xF3) {
                    if ((0x80 <= secondChar && secondChar <= 0x8F) && (0x80 <= thirdChar && thirdChar <= 0xBF) && (0x80 <= fourthChar && fourthChar <= 0xBF)) {
                        len = 4;
                    }
                }
            }
        }
        // 5个字节
        else if ((firstChar & 0xFC) == 0xF8) {
            len = 0;
        }
        // 6个字节
        else if ((firstChar & 0xFE) == 0xFC) {
            len = 0;
        }
        
        if (len == 0) {
            index++;
            [resData appendData:replacement];
        } else {
            [resData appendBytes:bytes + index length:len];
            index += len;
        }
    }
    
    return resData;
    
}

- (void)removeTimer {
    
    if (_scan_timeout_timer) {
       dispatch_source_cancel(_scan_timeout_timer);
        _scan_timeout_timer = nil;
    }
    
    if (_wait_timer) {
       dispatch_source_cancel(_wait_timer);
        _wait_timer = nil;
    }

}


#pragma mark BindSuccessViewControllerDelegate
- (void)didSeenewMydeviceBtnClick
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    [self.selectedWiflLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(28);
        make.top.equalTo(self.view.mas_top).offset(90);
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    [self.selectedWiflLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(28);
        make.top.equalTo(self.view.mas_top).offset(50+[UIDevice dev_navigationBarHeight]);
    }];

    return YES;
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    [self.selectedWiflLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(28);
        make.top.equalTo(self.view.mas_top).offset(50+[UIDevice dev_navigationBarHeight]);
    }];
}


@end
